package css.sword.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fastdfs.domain.StorePath;
import com.fastdfs.proto.storage.DownloadByteArray;
import com.fastdfs.service.FastFileStorageClient;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import css.sword.base.BaseController;
import css.sword.entity.DfsBaseInfo;
import css.sword.entity.DfsRelationShip;
import css.sword.entity.DfsTransferStatus;
import css.sword.mapper.DfsBaseInfoMapper;
import css.sword.mapper.DfsRelationShipMapper;
import css.sword.service.*;
import css.sword.util.*;
import io.swagger.annotations.*;
import org.apache.commons.io.FilenameUtils;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.*;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CountDownLatch;


@Controller("fileController")
@RequestMapping("/file")
@Api(tags = "文件上传，下载等服务", description = "文件服务文档说明", hidden = true)

public class FileController extends BaseController {

    private static String convertPdfMode = "wps";
    @Autowired
    protected FastFileStorageClient storageClient;
    Logger log = LoggerFactory.getLogger(FileController.class);


    @Autowired
    RedisDao redisDao;
    @Autowired
    DfsBaseInfoService dfsBaseInfoService;
    @Autowired
    DfsBaseInfoMapper dfsBaseInfoMapper;


    @Autowired
    DfsRelationShipMapper dfsRelationShipMapper;
    @Autowired
    SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    DfsTransferStatusService dfsTransferStatusService;
    // @Autowired
    @Qualifier("baseSqlSessionTemplate")
    SqlSessionTemplate sqlSessionTemplate;
    @Resource(name = "fileServiceImpl")
    private FileService fileService;
    private String localPdfPath = "C:\\";
    @Value("${transfer.startTime}")
    private String time;
    // @Value("${fastdfs.http_secret_key}")
    private String fastDFSHttpSecretKey;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DataSource dataSource;
    @Value("${wpsServer}")
    private String wpsServer;


    public static String getConvertPdfMode() {
        return convertPdfMode;
    }

    public static void setConvertPdfMode(String convertPdfMode) {
        FileController.convertPdfMode = convertPdfMode;
    }



    @ApiOperation(value="查询所有的人员",notes="查询所有的人员接口说明")
    @ApiImplicitParams({
            @ApiImplicitParam(name="month",value="年月，格式为：201801",dataType="String", paramType = "query"),
            @ApiImplicitParam(name="pageSize",value="页码",dataType="String", paramType = "query"),
            @ApiImplicitParam(name="pageNum",value="每页条数",dataType="String", paramType = "query"),
            @ApiImplicitParam(name="empName",value="业务员名称",dataType="String", paramType = "query"),
            @ApiImplicitParam(name="orderType",value="排序类型",dataType="String", paramType = "query"),
    })
    @ApiResponse(response=DfsBaseInfo.class, code = 200, message = "接口返回对象参数")
    @ResponseBody
    @RequestMapping(value = "/setConvertPdfMode", method = RequestMethod.GET, produces = "text/html; charset=UTF-8")
    public String setPdfMode(String convertPdfMode) throws Exception {

        FileController.convertPdfMode = convertPdfMode;
        if (StringUtils.isEmpty(convertPdfMode))
            FileController.convertPdfMode = "wps";
        Map<String, String> data = new HashMap<String, String>();
        data.put("convertPdfMode", convertPdfMode);
        return mapper.writeValueAsString(data);
    }

    @ResponseBody
    @RequestMapping(value = "/uploadDfs", method = RequestMethod.POST, produces = "text/html; charset=UTF-8")
    public String uploadDfs(String fileType, HttpServletRequest request, String userId, String md5, String moduleName, @RequestParam("file") MultipartFile file, HttpServletResponse response, String caToken) throws Exception {

        Map<String, String> data = new HashMap<String, String>();

        if (md5 == null) {
            return "md5为空";
        }
        String fileExt = FilenameUtils.getExtension(file.getOriginalFilename());
        data.put("userID", userId);
        data.put("moduleName", moduleName);
        data.put("md5", md5);
        data.put("secretKey", fileService.getToken(file.getOriginalFilename()));
        data.put("fileSize", file.getSize() + "");
        data.put("fileSrcName", file.getOriginalFilename());
        data.put("fileExt", fileExt);
        data.put("requestIP", getIp(request));
        data.put("fileType", URLConnection.getFileNameMap().getContentTypeFor(file.getOriginalFilename()));
        if (!fileService.isValid(fileExt)) {
            data.put("message", "上传类型不正确");
        } else if (fileExt.equalsIgnoreCase("wpss")) {
            return uploadDfsWpsSecure(caToken, "", "", file.getOriginalFilename(), request, userId, moduleName, file);
        } else {
            String url = fileService.upload(file, null, data, false, false, true);
            if (url == null) {
                data.put("message", "上传失败");
            } else {
                data.put("message", "上传成功json");
            }
        }
        // response.setContentType("text/html; charset=UTF-8");
        //JsonUtils.writeValue(response.getWriter(), data);
        return mapper.writeValueAsString(data);
    }

    @ResponseBody
    @RequestMapping(value = "/uploadDfsTaohong", method = RequestMethod.POST, produces = "text/html; charset=UTF-8")
    public String uploadDfsTaohong(String fileSrcName, String mergeRedPdfPath, String forceRefresh, String userId, String moduleName, String waterMark, @RequestParam("FileData") MultipartFile file, HttpServletResponse response, HttpServletRequest request) throws Exception {

        String uploadString = uploadDfsWps("", "", fileSrcName, request, userId, moduleName, file, "");
        Map dataMap = mapper.readValue(uploadString, Map.class);
        DfsRelationShip drs = new DfsRelationShip();
        drs.setFileSrcName(fileSrcName);
        if (StringUtils.isEmpty(mergeRedPdfPath)) {
            return uploadString;
        }
        drs.setMd5Path(dataMap.get("url").toString());
        String taohongString = mergeRedPdf(drs, mergeRedPdfPath, forceRefresh, userId, moduleName, waterMark, response, request);
        Map taohongMap = mapper.readValue(taohongString, Map.class);


        dataMap.put("taohongUrl", taohongMap.get("url"));
        dataMap.put("taohongMd5", taohongMap.get("md5"));
        dataMap.put("taohongfileSize", taohongMap.get("fileSize"));
        dataMap.put("taohongFilename", taohongMap.get("fileSrcName"));
        dataMap.remove("fileType");
        dataMap.remove("message");
        dataMap.remove("rwlzsx");
        dataMap.remove("cldid");
        dataMap.forEach((k, v) ->
                log.debug("k" + (k != null ? k.toString() : "") + "v" + (v != null ? v.toString() : ""))
        );
        return mapper.writeValueAsString(dataMap);
    }

    @ResponseBody
    @RequestMapping(value = "/uploadDfsWps", method = RequestMethod.POST, produces = "text/html; charset=UTF-8")
    public String uploadDfsWps(String cldid, String rwlzsx, String fileSrcName, HttpServletRequest request, String userId, String moduleName, @RequestParam("file") MultipartFile file, String caToken) throws Exception {

        Map<String, String> data = new HashMap<String, String>();
        DfsBaseInfo dfsBaseInfo = new DfsBaseInfo();
        Long fileSize = file.getSize();
        String fileExt = FilenameUtils.getExtension(file.getOriginalFilename());
        File tempFile = new File(
                System.getProperty("java.io.tmpdir") + "/upload_tmp" + UUID.randomUUID() + "." + fileExt);
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdirs();
        }
        file.transferTo(tempFile);
        if (fileExt.equalsIgnoreCase("wpss") && StringUtils.isNotEmpty(caToken)) {
            String destPlainDocPath = System.getProperty("java.io.tmpdir") + "/upload_tmp" + UUID.randomUUID() + ".docx";
            if (WpsSecureUtil.isSecurityDoc(tempFile.getAbsolutePath())) {
                log.debug(tempFile.getAbsolutePath() + " is a security doc!" + file.getOriginalFilename());
                log.debug(caToken);
                int ret = WpsSecureUtil.decryptSecurityDoc(tempFile.getAbsolutePath(), destPlainDocPath, caToken);
                if (ret == 0) {
                    log.debug("decrypt security doc succeed, result file path is : " + destPlainDocPath);
                    tempFile.delete();
                    tempFile = new File(destPlainDocPath);
                } else {
                    log.debug("解密安全文档失败");
                    data.put("message", "解密安全文档失败");
                }
            }
        }
        InputStream in = new FileInputStream(tempFile);
        String md5 = Md5Util.md5(in);
        dfsBaseInfo.setMd5Val(md5);
        in.close();
        dfsBaseInfo.setFileSize(fileSize);
        log.debug("fileSize", fileSize);
        dfsBaseInfo = fileService.md5Check(dfsBaseInfo);
        data.put("userID", userId);
        data.put("moduleName", moduleName);
        data.put("md5", md5);
        data.put("secretKey", fileService.getToken(file.getOriginalFilename()));
        data.put("fileSize", file.getSize() + "");
        data.put("fileSrcName", StringUtils.isEmpty(fileSrcName) ? file.getOriginalFilename() : fileSrcName);
        data.put("fileExt", fileExt);
        data.put("requestIP", getIp(request));
        data.put("fileType", URLConnection.getFileNameMap().getContentTypeFor(file.getOriginalFilename()));
        if (dfsBaseInfo != null && StringUtils.isNotEmpty(dfsBaseInfo.getMd5Val())) {
            DfsRelationShip drs = new DfsRelationShip();
            drs.setMd5Path(dfsBaseInfo.getMd5Val() + "@" + fileSize);
            drs.setFileSrcSystem(moduleName);
            drs.setUserDfsId(userId);
            if (StringUtils.isEmpty(fileSrcName))
                fileSrcName = file.getOriginalFilename();
            drs.setFileSrcName(fileSrcName);
            drs.setIsDel("0");
            drs.setIsTemp("0");
            drs.setFileSize(fileSize);
            drs.setSrcIpAddr(getIp(request));
            drs.setXgrDm(userId);
            drs.setXgrq(LocalDateTime.now());
            drs.setLrrDm(userId);
            drs.setSafeKey(fileService.getToken(file.getOriginalFilename()));
            drs.setFileType(URLConnection.getFileNameMap().getContentTypeFor(fileSrcName));
            drs.setLrrq(LocalDateTime.now());
            drs.setId(snowflakeIdWorker.nextId());
            fileService.insertDfsRelationShip(drs);

            data.put("url", dfsBaseInfo.getMd5Val() + "@" + dfsBaseInfo.getFileSize());
            data.put("message", "上传成功");
        } else {
            String url = fileService.upload(null, tempFile, data, false, false, true);
            if (url == null) {
                data.put("message", "上传失败");
            } else {
                data.put("message", "上传成功");
            }
        }
        data.put("rwlzsx", rwlzsx);
        data.put("cldid", cldid);
        tempFile.delete();
        // response.setContentType("text/html; charset=UTF-8");
        //JsonUtils.writeValue(response.getWriter(), data);
        if (tempFile.exists())
            tempFile.delete();
        return mapper.writeValueAsString(data);
        // return data;
    }

    @ResponseBody
    @RequestMapping(value = "/md5CheckUpload", method = RequestMethod.GET, produces = "text/html; charset=UTF-8")
    public String md5CheckUpload(String fileType, String fileSrcName, String md5, Long fileSize, String userId, String moduleName, HttpServletRequest request) throws Exception {
        Map<String, String> data = new HashMap<String, String>();
        DfsBaseInfo dfsBaseInfo = new DfsBaseInfo();
        dfsBaseInfo.setMd5Val(md5);
        dfsBaseInfo.setFileSize(fileSize);
        log.debug("fileSize", fileSize);
        dfsBaseInfo = fileService.md5Check(dfsBaseInfo);

        if (dfsBaseInfo != null && StringUtils.isNotEmpty(dfsBaseInfo.getMd5Val())) {
            DfsRelationShip drs = new DfsRelationShip();
            drs.setMd5Path(md5 + "@" + fileSize);
            drs.setFileSrcSystem(moduleName);
            drs.setUserDfsId(userId);
            drs.setFileSrcName(fileSrcName);
            drs.setIsDel("0");
            drs.setIsTemp("0");
            drs.setSafeKey(fileService.getToken(fileSrcName));
            data.put("secretKey", drs.getSafeKey());
            drs.setSrcIpAddr(getIp(request));
            drs.setXgrDm(userId);
            drs.setXgrq(LocalDateTime.now());
            drs.setLrrDm(userId);
            drs.setFileType(URLConnection.getFileNameMap().getContentTypeFor(fileSrcName));
            drs.setLrrq(LocalDateTime.now());
            drs.setId(snowflakeIdWorker.nextId());
            drs.setFileSize(fileSize);
            fileService.insertDfsRelationShip(drs);
            data.put("message", "0");
            data.put("url", dfsBaseInfo.getMd5Val() + "@" + dfsBaseInfo.getFileSize());
        } else {
            data.put("message", "正常上传");
        }
        // response.setContentType("text/html; charset=UTF-8");
        //JsonUtils.writeValue(response.getWriter(), data);
        log.debug("md5check" + md5);
        return mapper.writeValueAsString(data);
    }

    @ResponseBody
    @RequestMapping(value = "/md5Check", method = RequestMethod.GET, produces = "text/html; charset=UTF-8")
    public String md5Check(String md5, Long fileSize) throws JsonProcessingException {
        Map<String, String> data = new HashMap<String, String>();
        DfsBaseInfo dfsBaseInfo = new DfsBaseInfo();
        dfsBaseInfo.setMd5Val(md5);
        dfsBaseInfo.setFileSize(fileSize);
        log.debug("fileSize", fileSize);
        dfsBaseInfo = fileService.md5Check(dfsBaseInfo);

        if (dfsBaseInfo != null && StringUtils.isNotEmpty(dfsBaseInfo.getMd5Val())) {
            data.put("message", "0");
            data.put("url", dfsBaseInfo.getMd5Val() + "@" + dfsBaseInfo.getFileSize());
        } else {
            data.put("message", "正常上传");
        }
        // response.setContentType("text/html; charset=UTF-8");
        //JsonUtils.writeValue(response.getWriter(), data);
        // log.debug("md5check"+md5);
        return mapper.writeValueAsString(data);
        // return data;
    }

    @ResponseBody
    @RequestMapping(value = "/previewMd5", produces = "text/html;charset=UTF-8")
    public String previewMd5(DfsRelationShip drs, String waterMark, String forceRefresh, String xdocPdf, HttpServletResponse response, HttpServletRequest request) throws DocumentException {

        response.addHeader("pragma", "NO-cache");
        response.addHeader("Cache-Control", "no-cache");
        response.addDateHeader("Expries", 0);
        boolean isIE = false;
        String userAgent = request.getHeader("User-Agent").toLowerCase();
        if (userAgent.indexOf("msie") != -1 || userAgent.indexOf("trident") != -1)
            isIE = true;
        try {
            log.debug(drs + "drs" + drs.getMd5Path());
            if (drs == null || StringUtils.isBlank(drs.getMd5Path())) {
                response.getOutputStream().write("源文件参数错误".getBytes(StandardCharsets.UTF_8));
                response.getOutputStream().close();
                return "";
            }
            String fileSrcName = drs.getFileSrcName() != null ? drs.getFileSrcName().replaceAll("%28", "(").replaceAll("%29", ")").replaceAll("%27", "'").replaceAll("%21", "!").replaceAll("%3A", ":").replaceAll("%7E", "~").replaceAll("%40", "@").replaceAll("%23", "#").replaceAll("%25", "%").replaceAll("%26", "&").replaceAll("%2B", "+").replaceAll("%2A", "*") : "";
            drs = fileService.selectByMd5Path(drs);
            if (drs == null || StringUtils.isBlank(drs.getMd5Path())) {
                response.setStatus(404);
                response.getOutputStream().write("源文件不存在".getBytes(StandardCharsets.UTF_8));
                response.getOutputStream().close();
                return "";
            }
            if (StringUtils.isNotEmpty(fileSrcName))
                drs.setFileSrcName(fileSrcName);
            fileSrcName = drs.getFileSrcName();
            String fileExt = FilenameUtils.getExtension(drs.getFileSrcName());
            StorePath storePath = StorePath.praseFromUrl(drs.getFileId());
            if (fileExt.equals("") || fileExt.equals("null") || fileExt.length() > 4 || fileExt.contains("%") && !fileSrcName.contains(".zip.")) {
                byte[] abyte = storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), 0, 10, new DownloadByteArray());
                fileExt = FileType.getFileType(abyte);
                if (fileExt.equals("xml")) fileExt = "doc";
                fileSrcName += "." + fileExt;
                drs.setFileSrcName(fileSrcName);
                dfsRelationShipMapper.updateByPrimaryKeySelective(drs);
            }

//            if(!fileExt.equalsIgnoreCase("pdf")&&!fileExt.equalsIgnoreCase("docx")&&!fileExt.equalsIgnoreCase("doc")&&!fileExt.equalsIgnoreCase("pptx")&&!fileExt.equalsIgnoreCase("ppt")&&!fileExt.equalsIgnoreCase("xls")&&!fileExt.equalsIgnoreCase("xlsx")&&!fileExt.equalsIgnoreCase("txt")&&!fileExt.equalsIgnoreCase("png")&&!fileExt.equalsIgnoreCase("jpg")&&!fileExt.equalsIgnoreCase("bmp")&&!fileExt.equalsIgnoreCase("wps")){
//                response.getOutputStream().write("系统不支持非DOCX/PDF的文档格式预览".getBytes());
//                response.getOutputStream().close();
//                return;
//            }
            String pdfPath = "";
            String md5Path = drs.getMd5Path();
            forceRefresh = StringUtils.isEmpty(forceRefresh) ? "" : forceRefresh;
            if (fileExt.equalsIgnoreCase("pdf")) {
                return md5Path;
            } else if (StringUtils.isNotEmpty(drs.getPdfPath()) && !forceRefresh.equals("1")) {
                drs.setMd5Path(drs.getPdfPath());
                drs = fileService.selectByMd5Path(drs);
                drs.setFileSrcName(drs.getFileSrcName().substring(0, drs.getFileSrcName().lastIndexOf(".") + 1) + "pdf");
                if (StringUtils.isNotEmpty(drs.getFileId())) {
                    return drs.getMd5Path();
                }
            }
            drs.setMd5Path(md5Path);

            if (md5Path.endsWith("@0")) {
                return md5Path;
            }
            if (xdocPdf == null)
                xdocPdf = "";
            if (fileExt.equalsIgnoreCase("xlsx") || fileExt.equalsIgnoreCase("xls") || (fileExt.equalsIgnoreCase("docx") || fileExt.equalsIgnoreCase("doc") || fileExt.equalsIgnoreCase("wps") || fileExt.equalsIgnoreCase("wpss")) && convertPdfMode.equals("wps")) {
                //fileService.convertDocx2PdfStream(drs,waterMark,response);
                //pdfPath=HttpClientUtil.getInstance().httpGet(host+"/file/convertWps2Pdf");
                //pdfPath=fileService.convertOffice2PdfStream(drs,waterMark,"wps");
                Map map = new HashMap<String, String>();
                map.put("md5Path", drs.getMd5Path());
                map.put("fileSrcName", fileSrcName);
                drs.setFileSrcName(fileSrcName);
                String[] wpsArray = wpsServer.split(",");
                int length = wpsArray.length;
                int i = new Random().nextInt(length);
                String wpsHost = wpsArray[i];
                if ((fileExt.equalsIgnoreCase("docx") || fileExt.equalsIgnoreCase("doc")) && xdocPdf.equals("1"))
                    pdfPath = fileService.convertTxt2PdfStream(drs, waterMark, "1");
                else
                    pdfPath = HttpClientUtil.getInstance().httpPost(wpsHost + "/file/convertWps2Pdf", map, null);
                return pdfPath;
                //pdfPath=convertDoc2Pdf(drs,waterMark,response, request);
            } else if (fileExt.equalsIgnoreCase("txt")) {
//                    fileService.convertTxt2PdfStream(drs, waterMark, response);
                return fileService.convertTxt2PdfStream(drs, waterMark, "");
            } else if (fileExt.equalsIgnoreCase("jpg") || fileExt.equalsIgnoreCase("jpeg") || fileExt.equalsIgnoreCase("bmp") || fileExt.equalsIgnoreCase("tiff") || fileExt.equalsIgnoreCase("gif")) {
//                    fileService.convertTxt2PdfStream(drs, waterMark, response);
                return fileService.convertPic2PdfStream(drs, waterMark);
            } else {
                // fileService.convertOffice2PdfStream(drs,waterMark,response);
                return fileService.convertOffice2PdfStream(drs, waterMark, "libre");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    @RequestMapping(value = "/preview", produces = "application/pdf;charset=UTF-8")
    public void preview(DfsRelationShip drs, String waterMark, String forceRefresh, String xdocPdf, HttpServletResponse response, HttpServletRequest request) throws DocumentException {

        response.addHeader("pragma", "NO-cache");
        response.addHeader("Cache-Control", "no-cache");
        response.addDateHeader("Expries", 0);
        response.setContentType("application/pdf");
        response.setHeader("PDF-ENABLE-OPEN", "False");
        response.setHeader("PDF-SHOW-PATH", "False");
        request.setAttribute("logContent", "文件预览");
        boolean isIE = false;
        String userAgent = request.getHeader("User-Agent").toLowerCase();
        //log.debug(userAgent+"userAgent");
        if (userAgent.indexOf("msie") != -1 || userAgent.indexOf("trident") != -1)
            isIE = true;

        try {
            log.debug(drs + "drs" + drs.getMd5Path());
            if (drs == null || StringUtils.isBlank(drs.getMd5Path()) || drs.getMd5Path().endsWith("@0")) {
                response.getOutputStream().write("下载参数错误".getBytes(StandardCharsets.UTF_8));
                response.getOutputStream().close();
                return;
            }
            String fileSrcName = drs.getFileSrcName() != null ? drs.getFileSrcName().replaceAll("%28", "(").replaceAll("%29", ")").replaceAll("%27", "'").replaceAll("%21", "!").replaceAll("%3A", ":").replaceAll("%7E", "~").replaceAll("%40", "@").replaceAll("%23", "#").replaceAll("%25", "%").replaceAll("%26", "&").replaceAll("%2B", "+").replaceAll("%2A", "*") : "";
            drs = fileService.selectByMd5Path(drs);
            if (drs == null || StringUtils.isBlank(drs.getMd5Path())) {
                response.setStatus(404);
                response.getOutputStream().write("源文件不存在".getBytes(StandardCharsets.UTF_8));
                response.getOutputStream().close();
                return;
            }
            if (StringUtils.isNotEmpty(fileSrcName))
                drs.setFileSrcName(fileSrcName);
            fileSrcName = drs.getFileSrcName();
            String fileExt = FilenameUtils.getExtension(drs.getFileSrcName());
            StorePath storePath = StorePath.praseFromUrl(drs.getFileId());
            if (fileExt.equals("") || fileExt.equals("null") || fileExt.length() > 4 || fileExt.contains("%") && !fileSrcName.contains(".zip.")) {
                if (!drs.getMd5Path().substring(drs.getMd5Path().indexOf("@") + 1).equals("0")) {
                    byte[] abyte = storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), 0, 10, new DownloadByteArray());
                    log.debug(FileType.bytesToHexString(abyte));
                    fileExt = FileType.getFileType(abyte);
                    log.debug(fileExt);
                    if (fileExt.equals("xml")) fileExt = "doc";
                    fileSrcName += "." + fileExt;
                    drs.setFileSrcName(fileSrcName);
                    dfsRelationShipMapper.updateByPrimaryKeySelective(drs);
                }
            }
//            if(!fileExt.equalsIgnoreCase("pdf")&&!fileExt.equalsIgnoreCase("docx")&&!fileExt.equalsIgnoreCase("doc")&&!fileExt.equalsIgnoreCase("pptx")&&!fileExt.equalsIgnoreCase("ppt")&&!fileExt.equalsIgnoreCase("xls")&&!fileExt.equalsIgnoreCase("xlsx")&&!fileExt.equalsIgnoreCase("txt")&&!fileExt.equalsIgnoreCase("png")&&!fileExt.equalsIgnoreCase("jpg")&&!fileExt.equalsIgnoreCase("bmp")&&!fileExt.equalsIgnoreCase("wps")){
//                response.getOutputStream().write("系统不支持非DOCX/PDF的文档格式预览".getBytes());
//                response.getOutputStream().close();
//                return;
//            }
            String pdfPath = "";
            String md5Path = drs.getMd5Path();
            forceRefresh = StringUtils.isEmpty(forceRefresh) ? "" : forceRefresh;
            if (fileExt.equalsIgnoreCase("pdf")) {
                fileService.downloadStream(drs, response, isIE, false, true, false, null, "", false, waterMark);
                return;
            } else if (StringUtils.isNotEmpty(drs.getPdfPath()) && !forceRefresh.equals("1") && !drs.getPdfPath().equals("未解析")) {
                drs.setMd5Path(drs.getPdfPath());
                drs = fileService.selectByMd5Path(drs);
                drs.setFileSrcName(drs.getFileSrcName().substring(0, drs.getFileSrcName().lastIndexOf(".") + 1) + "pdf");
                if (StringUtils.isNotEmpty(drs.getFileId())) {
                    fileService.downloadStream(drs, response, isIE, false, true, false, null, "", false, waterMark);
                    return;
                }
            }
            drs.setMd5Path(md5Path);

            if (md5Path.endsWith("@0")) {
                Document document = new Document();
                try {
                    PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
                    document.open();
                    document.add(new Paragraph(" "));
                    document.close();
                    writer.close();
                } catch (DocumentException e) {
                    e.printStackTrace();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
            if (fileExt.equalsIgnoreCase("xlsx") || fileExt.equalsIgnoreCase("xls") || (fileExt.equalsIgnoreCase("docx") || fileExt.equalsIgnoreCase("doc") || fileExt.equalsIgnoreCase("wps")) && convertPdfMode.equals("wps")) {
                //fileService.convertDocx2PdfStream(drs,waterMark,response);
                //pdfPath=HttpClientUtil.getInstance().httpGet(host+"/file/convertWps2Pdf");
                //pdfPath=fileService.convertOffice2PdfStream(drs,waterMark,"wps");
                Map map = new HashMap<String, String>();
                map.put("md5Path", drs.getMd5Path());
                map.put("fileSrcName", fileSrcName);
                String[] wpsArray = wpsServer.split(",");
                int length = wpsArray.length;
                int i = new Random().nextInt(length);
                String wpsHost = wpsArray[i];

                if (xdocPdf == null)
                    xdocPdf = "";
                if ((fileExt.equalsIgnoreCase("docx") || fileExt.equalsIgnoreCase("doc")) && xdocPdf.equals("1")) {
                    try {
                        pdfPath = fileService.convertTxt2PdfStream(drs, waterMark, "1");
                    } catch (Exception e) {
//                        e.printStackTrace();
                        log.error(e.getMessage() + "本地转版失败，尝试调用wps windows 转版");
                        pdfPath = HttpClientUtil.getInstance().httpPost(wpsHost + "/file/convertWps2Pdf", map, null);
                    }
                } else
                    pdfPath = HttpClientUtil.getInstance().httpPost(wpsHost + "/file/convertWps2Pdf", map, null);
                //pdfPath=convertDoc2Pdf(drs,waterMark,response, request);
            } else if (fileExt.equalsIgnoreCase("txt")) {
//                    fileService.convertTxt2PdfStream(drs, waterMark, response);
                pdfPath = fileService.convertTxt2PdfStream(drs, waterMark, "");
            } else if (fileExt.equalsIgnoreCase("jpg") || fileExt.equalsIgnoreCase("jpeg") || fileExt.equalsIgnoreCase("bmp") || fileExt.equalsIgnoreCase("tif") || fileExt.equalsIgnoreCase("gif") || fileExt.equalsIgnoreCase("tiff")) {
//                    fileService.convertTxt2PdfStream(drs, waterMark, response);
                pdfPath = fileService.convertPic2PdfStream(drs, waterMark);
            } else {
                // fileService.convertOffice2PdfStream(drs,waterMark,response);
                pdfPath = fileService.convertOffice2PdfStream(drs, waterMark, "libre");
            }
            if (StringUtils.isEmpty(pdfPath)) {
                response.getOutputStream().write("转换失败".getBytes(StandardCharsets.UTF_8));
                response.getOutputStream().close();
                return;
            }
            if (StringUtils.isNotEmpty(pdfPath) && !pdfPath.equals("未解析")) {
                log.debug(pdfPath + "hhhhhhhhhhhhhhhhhhhhh");
                drs.setMd5Path(pdfPath);
                drs = fileService.selectByMd5Path(drs);
                drs.setFileSrcName(drs.getFileSrcName().substring(0, drs.getFileSrcName().lastIndexOf(".") + 1) + "pdf");
                if (StringUtils.isNotEmpty(drs.getFileId())) {
                    fileService.downloadStream(drs, response, isIE, false, true, false, null, "", false, waterMark);
                    return;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/convertWps2Pdf", produces = "text/html;charset=UTF-8")
    public String convertDoc2Pdf(DfsRelationShip drs, String waterMark, HttpServletResponse response, HttpServletRequest request) throws DocumentException {


        response.addHeader("pragma", "NO-cache");
        response.addHeader("Cache-Control", "no-cache");
        response.addDateHeader("Expries", 0);
        try {
            log.debug(drs + "drs" + drs.getMd5Path());
            if (drs == null || StringUtils.isBlank(drs.getMd5Path())) {
                return "源文件下载参数错误";
            }
            String fileSrcName = drs.getFileSrcName() != null ? drs.getFileSrcName().replaceAll("%28", "(").replaceAll("%29", ")").replaceAll("%27", "'").replaceAll("%21", "!").replaceAll("%3A", ":").replaceAll("%7E", "~").replaceAll("%40", "@").replaceAll("%23", "#").replaceAll("%25", "%").replaceAll("%26", "&").replaceAll("%2B", "+").replaceAll("%2A", "*") : "";
            drs = fileService.selectByMd5Path(drs);
            if (drs == null || StringUtils.isBlank(drs.getMd5Path())) {
                return "源文件不存在";
            }
            if (StringUtils.isNotEmpty(fileSrcName))
                drs.setFileSrcName(fileSrcName);

            String fileExt = FilenameUtils.getExtension(drs.getFileSrcName());
            return fileService.convertOffice2PdfStream(drs, waterMark, "wps");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "convert error";
    }

    @ResponseBody
    @RequestMapping(value = "/mergeRedPdf", produces = "text/html;charset=UTF-8")
    public String mergeRedPdf(DfsRelationShip drs, String mergeRedPdfPath, String forceRefresh, String userId, String moduleName, String waterMark, HttpServletResponse response, HttpServletRequest request) throws IOException, DocumentException {
        Map<String, String> data = new HashMap<String, String>();
        log.debug(drs + "drs" + drs.getMd5Path());
        if (drs == null || StringUtils.isBlank(drs.getMd5Path())) {
            return "下载参数错误";
        }
        try {
            String fileSrcName = drs.getFileSrcName() != null ? drs.getFileSrcName().replaceAll("%28", "(").replaceAll("%29", ")").replaceAll("%27", "'").replaceAll("%3A", ":").replaceAll("%21", "!").replaceAll("%7E", "~").replaceAll("%40", "@").replaceAll("%23", "#").replaceAll("%25", "%").replaceAll("%26", "&").replaceAll("%2B", "+").replaceAll("%2A", "*") : "";
            drs = fileService.selectByMd5Path(drs);
            if (drs == null || StringUtils.isBlank(drs.getMd5Path())) {
                return "文件不存在";
            }
            if (StringUtils.isNotEmpty(fileSrcName))
                drs.setFileSrcName(fileSrcName);
            String fileExt = FilenameUtils.getExtension(drs.getFileSrcName());
            if (!fileExt.equalsIgnoreCase("pdf") && !fileExt.equalsIgnoreCase("docx") && !fileExt.equalsIgnoreCase("doc") && !fileExt.equalsIgnoreCase("wpss")) {
                return "系统不支持非DOCX/PDF的文档套红";
            }
            data.put("userID", userId);
            data.put("moduleName", moduleName);
            data.put("requestIP", getIp(request));
            if (StringUtils.isNotEmpty(mergeRedPdfPath)) {
                DfsRelationShip drsRed = new DfsRelationShip();
                drsRed.setMd5Path(mergeRedPdfPath);
                drsRed = fileService.selectByMd5Path(drsRed);
                if (drsRed == null || StringUtils.isBlank(drsRed.getMd5Path())) {
                    return "红头文件不存在";
                }
                fileService.mergeRedDocx2PdfStream(drs, mergeRedPdfPath, data, waterMark, convertPdfMode, forceRefresh);
            } else {
                String res = previewMd5(drs, waterMark, forceRefresh, "", response, request);
                fileSrcName = drs.getFileSrcName().substring(0, drs.getFileSrcName().lastIndexOf(".") + 1) + "pdf";
                data.put("url", res);
                data.put("fileSrcName", fileSrcName);
                data.put("md5", res.substring(0, res.indexOf("@")));
                data.put("fileSize", res.substring(res.indexOf("@") + 1));
                data.put("userId", userId);
                data.put("moduleName", moduleName);
                data.put("waterMark", waterMark);
            }
        } catch (IOException e) {
            e.printStackTrace();
            data.put("message", e.getMessage());
        }
        return mapper.writeValueAsString(data);
    }

    @RequestMapping(value = "/download")
    public void download(DfsRelationShip drs, String isPreview, String forceDocx, HttpServletResponse response, HttpServletRequest request, String webOffice, String wordWaterMark, String isWpsSecure, String caToken, String waterMark) {

        response.addHeader("pragma", "NO-cache");
        response.addHeader("Cache-Control", "no-cache");
        response.addDateHeader("Expries", 0);

        request.setAttribute("logContent", "文件下载");
        try {
            log.debug(drs + "drs" + drs.getMd5Path());
            if (drs == null || StringUtils.isBlank(drs.getMd5Path())) {
                response.getOutputStream().write("download parameter error".getBytes());
                response.getOutputStream().close();
                return;
            }
            boolean iWebOffice = false;
            if (StringUtils.isNotEmpty(webOffice) && webOffice.equals("1"))
                iWebOffice = true;
//
//            log.debug(redisUtil.get("String:fileAllow:identityId:43436EC541AD476AAF90D164BF4A8CED"));
//
            String fileSrcName = drs.getFileSrcName() != null ? drs.getFileSrcName().replaceAll("%28", "(").replaceAll("%29", ")").replaceAll("%27", "'").replaceAll("%3A", ":").replaceAll("%21", "!").replaceAll("%7E", "~").replaceAll("%40", "@").replaceAll("%23", "#").replaceAll("%25", "%").replaceAll("%26", "&").replaceAll("%2B", "+").replaceAll("%2A", "*") : "";
            log.debug(fileSrcName + "bbbbbbbbbbbbbbbbbbbbb");
//            if(StringUtils.isNotEmpty(fileSrcName))
//                fileSrcName= URLDecoder.decode(fileSrcName,"UTF-8");
            log.debug(fileSrcName + "cccccccccccccccccccccc");
            drs = fileService.selectByMd5Path(drs);
            if (drs == null || StringUtils.isBlank(drs.getMd5Path())) {
                response.getOutputStream().write("0".getBytes());
                response.getOutputStream().close();
                response.setStatus(404);
                return;
            }
            if (StringUtils.isNotEmpty(fileSrcName))
                drs.setFileSrcName(fileSrcName);
            fileSrcName = drs.getFileSrcName();
            String fileExt = FilenameUtils.getExtension(drs.getFileSrcName());
            if (!iWebOffice && (StringUtils.isNotEmpty(isWpsSecure) && isWpsSecure.equals("1")) || drs.getIsWpsSecure().equals("1")) {
                if (StringUtils.isEmpty(caToken) && !iWebOffice) {
                    response.getOutputStream().write("caToken is empty".getBytes());
                    response.getOutputStream().close();
                    response.setStatus(500);
                    return;
                }
                fileService.downloadStream(drs, response, false, false, false, iWebOffice, null, caToken, true, waterMark);
            } else {
                StorePath storePath = StorePath.praseFromUrl(drs.getFileId());
                if ((fileExt.equals("") || fileExt.equals("null") || fileExt.length() > 4 || fileExt.contains("%")) && !fileSrcName.contains(".zip.")) {
                    byte[] abyte = storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), 0, 10, new DownloadByteArray());
                    log.debug(FileType.bytesToHexString(abyte));
                    fileExt = FileType.getFileType(abyte);
                    log.debug(fileExt);
                    if (fileExt.equals("xml")) fileExt = "doc";
                    fileSrcName += "." + fileExt;
                    drs.setFileSrcName(fileSrcName);
                    dfsRelationShipMapper.updateByPrimaryKeySelective(drs);
                }

                if (StringUtils.isNotEmpty(wordWaterMark) && (fileExt.equalsIgnoreCase("docx") || fileExt.equalsIgnoreCase("doc") || fileExt.equalsIgnoreCase("wps"))) {
                    response.setContentType("application/octet-stream");
                    fileSrcName = new String(fileSrcName.getBytes(StandardCharsets.UTF_8), "ISO8859_1");
                    log.debug(fileSrcName);
                    response.addHeader("Content-Disposition", "attachment;filename=\"" + fileSrcName + "\"");
                    String[] wpsArray = wpsServer.split(",");
                    int length = wpsArray.length;
                    int i = new Random().nextInt(length);
                    String wpsHost = wpsArray[i];
                    HttpClientUtil.getInstance().httpDownloadFile(wpsHost + "/file/downloadWpsWaterMark?md5Path=" + drs.getMd5Path() + "&staticToken=f1634ed30b374f159a684ef353184f16&waterMark=" + URLEncoder.encode(wordWaterMark, "UTF-8"), response, null);
                    return;
                }

                if (StringUtils.isNotBlank(isPreview) && isPreview.equals("1") && (FilenameUtils.getExtension(drs.getFileSrcName()).equals("pdf"))) {
                    response.setContentType("application/pdf");
                } else {
                    response.setContentType("application/octet-stream");
                }
                boolean isIE = false;
                String userAgent = request.getHeader("User-Agent").toLowerCase();
                log.debug(userAgent + "userAgent" + "weboffice:" + webOffice + " ");
                boolean convertDocx = StringUtils.isNotBlank(forceDocx) && forceDocx.equals("1") && (FilenameUtils.getExtension(drs.getFileSrcName()).equals("doc"));
                if (userAgent.indexOf("msie") != -1 || userAgent.indexOf("trident") != -1)
                    isIE = true;

                fileService.downloadStream(drs, response, isIE, convertDocx, false, iWebOffice, null, "", false, waterMark);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/downloadWpsWaterMark")
    public void downloadWpsWaterMark(DfsRelationShip drs, HttpServletResponse response, String waterMark) {

        response.addHeader("pragma", "NO-cache");
        response.addHeader("Cache-Control", "no-cache");
        response.addDateHeader("Expries", 0);
        try {
            log.debug(drs + "drs" + drs.getMd5Path());
            if (drs == null || StringUtils.isBlank(drs.getMd5Path())) {
                response.getOutputStream().write("download parameter error".getBytes());
                response.getOutputStream().close();
                return;
            }
            drs = fileService.selectByMd5Path(drs);
            if (drs == null || StringUtils.isBlank(drs.getMd5Path())) {
                response.getOutputStream().write("0".getBytes());
                response.getOutputStream().close();
                response.setStatus(404);
                return;
            }

            fileService.downloadStream(drs, response, false, false, false, false, waterMark, "", false, null);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/downloadPackage")
    public void downloadPackage(String[] md5Paths, String[] fileNames, String zipName, HttpServletResponse response, HttpServletRequest request, String waterMark) throws IOException {

        response.addHeader("pragma", "NO-cache");
        response.addHeader("Cache-Control", "no-cache");
        response.addDateHeader("Expries", 0);
        request.setAttribute("logContent", "文件打包下载");
        try {
            log.debug(md5Paths + "drs");
            if ((StringUtils.isBlank(zipName) || md5Paths == null) || (fileNames != null && fileNames.length != md5Paths.length)) {
                response.getOutputStream().write("打包下载参数错误".getBytes());
                response.getOutputStream().close();
                return;
            }
            boolean isIE = false;
            String userAgent = request.getHeader("User-Agent").toLowerCase();
            log.debug(userAgent + "userAgent");
            if (userAgent.indexOf("msie") != -1 || userAgent.indexOf("trident") != -1)
                isIE = true;
            fileService.downloadPackageStream(md5Paths, fileNames, zipName, response, isIE, waterMark);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 下载文件服务器本地硬盘文件 支持断点下载
    @RequestMapping(value = "/downloadLocal", method = RequestMethod.GET)
    public void downloadLocal(String urlName, String isPreview, HttpServletResponse response,
                              HttpServletRequest request) {
        response.reset();
        response.addHeader("pragma", "NO-cache");
        response.addHeader("Cache-Control", "no-cache");
        response.addDateHeader("Expries", 0);

        if (StringUtils.isNotEmpty(isPreview)) {
            request.setAttribute("logContent", "预览PDF");
            response.setContentType("application/pdf");
        } else {
            request.setAttribute("logContent", "下载服务器本地文件");
            response.setContentType("application/octet-stream");
        }
        FileInputStream fis = null;
        OutputStream out = null;
        try {
            log.debug(urlName + "准备下载");
            String filePath = "";
            // log.debug(localPdfPath);
            if (urlName.indexOf("\\") == -1 && urlName.indexOf("/") == -1)
                filePath = localPdfPath + urlName;

            File file = new File(filePath);
            long length = file.length();
            // url.substring(url.lastIndexOf("/") + 1, url.length())
            boolean isIE = false;
            String userAgent = request.getHeader("User-Agent").toLowerCase();
            log.debug(userAgent);
            if (userAgent.indexOf("msie") != -1 || userAgent.indexOf("trident") != -1)
                isIE = true;
            if (!isIE)
                urlName = new String(file.getName().getBytes(), "ISO8859_1");
            else
                urlName = URLEncoder.encode(file.getName(), "UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + urlName);
            String range = request.getHeader("Range");
            int from = 0;
            int to = (int) length;
            if (range != null) {
                if (range.startsWith("bytes=")) {
                    int index = range.indexOf('-', "bytes=".length());
                    from = Integer.parseInt(range.substring("bytes=".length(), index));
                    if (index != range.length() - 1)
                        to = Integer.parseInt(range.substring(index + 1));
                }
                response.setHeader("Content-Range", "bytes " + from + "-" + (to - 1) + "/" + length);
                response.setHeader("Accept-Ranges", "bytes");
                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            }
            response.addHeader("Content-Length", to - from + "");
            response.setContentLength(to - from);
            fis = new FileInputStream(file);
            byte[] buff = new byte[4096];
            int readed;
            fis.skip(from);
            int count = to - from;
            int total = 0;
            out = response.getOutputStream();
            while ((readed = fis.read(buff)) > 0) {
                total += readed;
                if (total >= count) {
                    out.write(buff, 0, (readed - (total - count)));
                    break;
                } else
                    out.write(buff, 0, readed);
            }
            fis.close();
            fis = null;
            out.flush();
            out.close();
            out = null;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @GetMapping(value = "showLog")
    public String showMenu(Model model) {
        return "/system/log/logList";
    }

    @ResponseBody
//    @GetMapping(value = "fileTransfer")
    public String fileTransfer(Model model) throws InterruptedException {

        CountDownLatch c = new CountDownLatch(3);
//        List<Map<String, Object>> infoList = jdbcTemplate.queryForList("SELECT * FROM (SELECT A.*, ROWNUM RN FROM (select id,file_name,extention,save_path,save_time,user_id from ta_horizon_info where  save_path like 'css:%' order by save_time desc  )A WHERE ROWNUM <= 15000000)WHERE RN >=1");
//        List<Map<String, Object>> documentList = jdbcTemplate.queryForList("SELECT * FROM (SELECT A.*, ROWNUM RN FROM (select  distinct documentid as id,subject as file_name,filetype as extention, htmlpath as save_path,filedate as save_time,authorid as user_id from DOCUMENT where  htmlpath like 'css:%'  order by documentid desc )A WHERE ROWNUM <= 15000000)WHERE RN >=1");
//        List<Map<String, Object>> documentPdfList = jdbcTemplate.queryForList("SELECT * FROM (SELECT A.*, ROWNUM RN FROM (select distinct id,filename as file_name,type as extention,path as save_path,datetime as save_time,userid as user_id from document_pdf where path like 'css:%' order by to_date(datetime,'yyyy-mm-dd hh24:mi:ss') desc  )A WHERE ROWNUM <= 15000000)WHERE RN >=1");

        List<Map<String, Object>> infoList = jdbcTemplate.queryForList("SELECT * FROM (SELECT A.*, ROWNUM RN FROM (select id,file_name,extention,save_path,save_time,user_id from ta_horizon_info where (to_date('" + time + "','yyyy-mm-dd hh24:mi:ss')>to_date(SUBSTR(save_time,0,19),'yyyy-mm-dd hh24:mi:ss') and to_date(SUBSTR(save_time,0,19),'yyyy-MM-dd HH24:mi:ss')>to_date('2017-08-1 00:00:01','yyyy-mm-dd hh24:mi:ss'))  and save_path like 'css:%' order by save_time desc  )A WHERE ROWNUM <= 15000000)WHERE RN >=1");
        List<Map<String, Object>> documentList = jdbcTemplate.queryForList("SELECT * FROM (SELECT A.*, ROWNUM RN FROM (select  distinct documentid as id,subject as file_name,filetype as extention, htmlpath as save_path,filedate as save_time,authorid as user_id from DOCUMENT where  htmlpath like 'css:%' and (filedate like '%-18') order by documentid desc )A WHERE ROWNUM <= 50000)WHERE RN >=1");
        List<Map<String, Object>> documentPdfList = jdbcTemplate.queryForList("SELECT * FROM (SELECT A.*, ROWNUM RN FROM (select distinct id,filename as file_name,type as extention,path as save_path,datetime as save_time,userid as user_id from document_pdf where to_date('" + time + "','yyyy-mm-dd hh24:mi:ss')>to_date(SUBSTR(datetime,0,19),'yyyy-mm-dd hh24:mi:ss') and to_date(SUBSTR(datetime,0,19),'yyyy-MM-dd HH24:mi:ss')>to_date('2017-08-1 00:00:00','yyyy-mm-dd hh24:mi:ss') and path like 'css:%' order by to_date(datetime,'yyyy-mm-dd hh24:mi:ss') desc  )A WHERE ROWNUM <= 15000000)WHERE RN >=1");

        List<DfsTransferStatus> infoListed = dfsTransferStatusService.list(new QueryWrapper<DfsTransferStatus>().eq("SUCCESS_FLAG", "1").eq("module_name", "szoa1info").or(i -> i.like("memo", "ound").eq("success_flag", "0")));
        List<DfsTransferStatus> documentListed = dfsTransferStatusService.list(new QueryWrapper<DfsTransferStatus>().eq("SUCCESS_FLAG", "1").eq("module_name", "szoa1document"));
        List<DfsTransferStatus> documentPdfListed = dfsTransferStatusService.list(new QueryWrapper<DfsTransferStatus>().eq("SUCCESS_FLAG", "1").eq("module_name", "szoa1documentPdf"));

        log.debug(infoListed.size() + "");
        log.debug(documentListed.size() + "");
        log.debug(documentPdfListed.size() + "");

        long startTotalTime = System.currentTimeMillis();

        new Thread(new Runnable() {
            @Override
            public void run() {
                long fileSize = 0;
                for (int i = 0; i < infoList.size(); i++) {
                    Map<String, Object> map = infoList.get(i);
                    DfsTransferStatus dfsTransferStatus = new DfsTransferStatus();
                    //   log.debug(map.get("id").toString()+map.get("save_path").toString());
                    dfsTransferStatus.setBussinessId(map.get("id").toString());
                    dfsTransferStatus.setSavePath(map.get("save_path").toString());
                    if (infoListed.contains(dfsTransferStatus)) {
                        // log.debug(dfsTransferStatus+"已被迁移");
                        continue;
                    }
                    File file = new File("z:\\fileservice\\store\\" + StringUtils.splitFileId(map.get("save_path").toString().substring(4)));
//                    if (!file.exists()) {
//                        continue;
//                    }
                    if (file.exists())
                        fileSize += file.length();
                    log.debug("开始迁移第" + (i + 1) + "个文件，本次迁移info表记录共 " + infoList.size() + " 个文件,已迁移 " + (fileSize * 1.0 / 1024 / 1024) + " MB,单表已耗时 " + ((System.currentTimeMillis() - startTotalTime) / 1000) + " 秒");
                    try {
                        fileService.fileListTransfer(map, "info");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                log.debug("迁移Info表结束，共迁移" + (infoList.size()) + "个文件，已迁移 " + (fileSize * 1.0 / 1024 / 1024) + " MB,总耗时 " + ((System.currentTimeMillis() - startTotalTime) / 1000) + " 秒");
                c.countDown();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                long fileSize = 0;
                Long firstFileSize = fileSize;
                long startDocumentTime = System.currentTimeMillis();
                for (int i = 0; i < documentList.size(); i++) {
                    Map<String, Object> map = documentList.get(i);
                    DfsTransferStatus dfsTransferStatus = new DfsTransferStatus();
                    dfsTransferStatus.setBussinessId(map.get("id").toString());
                    dfsTransferStatus.setSavePath(map.get("save_path").toString());
                    if (documentListed.contains(dfsTransferStatus)) {
                        // log.debug(dfsTransferStatus+"已被迁移");
                        continue;
                    }
                    File file = new File("z:\\fileservice\\store\\" + StringUtils.splitFileId(map.get("save_path").toString().substring(4)));
//                      if (!file.exists())
//                          continue;
                    if (file.exists())
                        fileSize += file.length();
                    log.debug("开始迁移第" + (i + 1) + "个文件，本次迁移document表记录共 " + documentList.size() + " 个文件,已迁移 " + (fileSize * 1.0 / 1024 / 1024) + " MB,单表已耗时 " + ((System.currentTimeMillis() - startDocumentTime) / 1000) + " 秒.总耗时 " + ((System.currentTimeMillis() - startTotalTime) / 1000) + " 秒");
                    try {
                        fileService.fileListTransfer(map, "document");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                c.countDown();
                log.debug("迁移document表结束，共迁移" + (infoList.size() + documentList.size()) + "个文件，共迁移 " + (fileSize * 1.0 / 1024 / 1024) + " MB,其中document表迁移 " + ((fileSize - firstFileSize) / 1024 / 1024) + " MB,总耗时 " + ((System.currentTimeMillis() - startTotalTime) / 1000) + " 秒");
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                long fileSize = 0;
                long startDocumentPdfTime = System.currentTimeMillis();
                for (int i = 0; i < documentPdfList.size(); i++) {
                    Map<String, Object> map = documentPdfList.get(i);
                    String key = map.get("id").toString() + map.get("save_path");
                    DfsTransferStatus dfsTransferStatus = new DfsTransferStatus();
                    dfsTransferStatus.setBussinessId(map.get("id").toString());
                    dfsTransferStatus.setSavePath(map.get("save_path").toString());
                    if (documentPdfListed.contains(dfsTransferStatus)) {
                        // log.debug(dfsTransferStatus+"已被迁移");
                        continue;
                    }
                    File file = new File("z:\\fileservice\\store\\" + StringUtils.splitFileId(map.get("save_path").toString().substring(4)));
//                    if (!file.exists())
//                        continue;
                    if (file.exists())
                        fileSize += file.length();
                    log.debug("开始迁移第" + (i + 1) + "个文件，本次迁移documentPdf表记录共 " + documentPdfList.size() + " 个文件,已迁移 " + (fileSize * 1.0 / 1024 / 1024) + " MB,单表已耗时 " + ((System.currentTimeMillis() - startDocumentPdfTime) * 1.0 / 1000) + " 秒.总耗时 " + ((System.currentTimeMillis() - startTotalTime) / 1000) + " 秒");
                    try {
                        fileService.fileListTransfer(map, "documentPdf");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                log.debug("迁移documentPdf表结束，共迁移" + (documentPdfList.size()) + "个文件，已迁移 " + (fileSize * 1.0 / 1024 / 1024) + " MB,总耗时 " + ((System.currentTimeMillis() - startDocumentPdfTime) / 1000) + " 秒");

                c.countDown();
            }
        }).start();

        c.await();
        log.debug("迁移结束，共迁移" + (infoList.size() + documentList.size() + documentPdfList.size()) + "个文件，总耗时 " + ((System.currentTimeMillis() - startTotalTime) / 1000) + " 秒");

        // System.out.println(list);
        return "success";
    }

    @ResponseBody
    @RequestMapping(value = "/uploadDfsWpsSecure", method = RequestMethod.POST, produces = "text/html; charset=UTF-8")
    public String uploadDfsWpsSecure(String caToken, String cldid, String rwlzsx, String fileSrcName, HttpServletRequest request, String userId, String moduleName, @RequestParam("file") MultipartFile file) throws Exception {

        Map<String, String> data = new HashMap<String, String>();
        DfsBaseInfo dfsBaseInfo = new DfsBaseInfo();
        Long fileSize = file.getSize();
        String fileExt = FilenameUtils.getExtension(file.getOriginalFilename());
        File tempFile = new File(
                System.getProperty("java.io.tmpdir") + "/upload_tmp" + UUID.randomUUID() + "." + fileExt);
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdirs();
        }
        file.transferTo(tempFile);
        String destPlainDocPath = System.getProperty("java.io.tmpdir") + "/upload_tmp" + UUID.randomUUID() + ".docx";
        if (WpsSecureUtil.isSecurityDoc(tempFile.getAbsolutePath())) {
            log.debug(tempFile.getAbsolutePath() + " is a security doc!" + file.getOriginalFilename());
            log.debug(caToken);
            int ret = WpsSecureUtil.decryptSecurityDoc(tempFile.getAbsolutePath(), destPlainDocPath, caToken);
            if (ret == 0) {
                log.debug("decrypt security doc succeed, result file path is : " + destPlainDocPath);
            } else {
                log.debug("解密安全文档失败");
                data.put("message", "解密安全文档失败");
                return mapper.writeValueAsString(data);
            }
        }
        tempFile.delete();
        tempFile = new File(destPlainDocPath);
        InputStream in = new FileInputStream(tempFile);
        String md5 = Md5Util.md5(in);
        dfsBaseInfo.setMd5Val(md5);
        in.close();
        dfsBaseInfo.setFileSize(tempFile.length());
        log.debug("fileSize" + tempFile.length() + "md5" + md5);
        dfsBaseInfo = fileService.md5Check(dfsBaseInfo);
        if (dfsBaseInfo != null) {
            dfsBaseInfo.setIsWpsSecure("1");
            dfsBaseInfoService.update(dfsBaseInfo, new UpdateWrapper<DfsBaseInfo>().eq("MD5_VAL", dfsBaseInfo.getMd5Val()).eq("FILE_SIZE", dfsBaseInfo.getFileSize()));
            log.debug("fileSize" + dfsBaseInfo.getMd5Val() + "md5" + dfsBaseInfo.getFileSize());
        }
        data.put("userID", userId);
        data.put("moduleName", moduleName);
        data.put("md5", md5);
        data.put("secretKey", fileService.getToken(file.getOriginalFilename()));
        data.put("caToken", caToken);
        data.put("fileSize", tempFile.length() + "");
        data.put("fileSrcName", StringUtils.isEmpty(fileSrcName) ? (file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")) + ".docx") : fileSrcName.substring(0, fileSrcName.lastIndexOf(".")) + ".docx");
        data.put("fileExt", "docx");
        data.put("requestIP", getIp(request));
        data.put("fileType", URLConnection.getFileNameMap().getContentTypeFor(file.getOriginalFilename()));
        data.put("isWpsSecure", "1");

        if (dfsBaseInfo != null && StringUtils.isNotEmpty(dfsBaseInfo.getMd5Val())) {
            DfsRelationShip drs = new DfsRelationShip();
            drs.setMd5Path(dfsBaseInfo.getMd5Val() + "@" + tempFile.length());
            drs.setFileSrcSystem(moduleName);
            drs.setUserDfsId(userId);
            if (StringUtils.isEmpty(fileSrcName))
                fileSrcName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")) + ".docx";
            drs.setFileSrcName(fileSrcName);
            drs.setIsDel("0");
            drs.setIsTemp("0");
            drs.setFileSize(tempFile.length());
            drs.setSrcIpAddr(getIp(request));
            drs.setXgrDm(userId);
            drs.setXgrq(LocalDateTime.now());
            drs.setLrrDm(userId);
            drs.setSafeKey(fileService.getToken(file.getOriginalFilename()));
            drs.setFileType(URLConnection.getFileNameMap().getContentTypeFor(fileSrcName));
            drs.setLrrq(LocalDateTime.now());
            drs.setId(snowflakeIdWorker.nextId());
            drs.setIsWpsSecure("1");
            fileService.insertDfsRelationShip(drs);

            data.put("url", dfsBaseInfo.getMd5Val() + "@" + dfsBaseInfo.getFileSize());
            data.put("message", "解密上传成功");
        } else {
            String url = fileService.upload(null, tempFile, data, false, false, true);
            if (url == null) {
                data.put("message", "上传失败");
            } else {
                data.put("message", "上传成功");
            }
        }
        data.put("rwlzsx", rwlzsx);
        data.put("cldid", cldid);
        data.put("isWpsSecure", "1");
        tempFile.delete();
        // response.setContentType("text/html; charset=UTF-8");
        //JsonUtils.writeValue(response.getWriter(), data);
//        if (tempFile.exists())
//            tempFile.delete();
        return mapper.writeValueAsString(data);
        // return data;
    }

    @ResponseBody
    @GetMapping(value = "preparePdf")
    public String preparePdf(Model model) throws InterruptedException {
        List<DfsBaseInfo> infoListed = dfsBaseInfoService.list(new QueryWrapper<DfsBaseInfo>().ge("lrrq", LocalDate.parse("2018-12-05")).isNull("pdf_path").orderByDesc("lrrq"));
        log.debug(infoListed.size() + "");
        String[] wpsArray = wpsServer.split(",");
        int length = wpsArray.length;
        for (DfsBaseInfo dfsBaseInfo : infoListed
        ) {
            if (dfsBaseInfo.getFileExt().equalsIgnoreCase("doc") || dfsBaseInfo.getFileExt().equalsIgnoreCase("docx") || dfsBaseInfo.getFileExt().equalsIgnoreCase("xls") || dfsBaseInfo.getFileExt().equalsIgnoreCase("xlsx")) {

                int i = new Random().nextInt(length);
                String wpsHost = wpsArray[i];
                log.debug(HttpClientUtil.getInstance().httpGet(wpsHost + "/file/previewMd5?md5Path=" + dfsBaseInfo.getMd5Val() + "@" + dfsBaseInfo.getFileSize(), null));
            }
        }
        return "success";
    }

    @RequestMapping(value = "/imagesToPdf")
    public void imagesToPdf(String[] md5Paths, String pdfName, HttpServletResponse response, HttpServletRequest request, String waterMark) throws IOException {

        response.addHeader("pragma", "NO-cache");
        response.addHeader("Cache-Control", "no-cache");
        response.addDateHeader("Expries", 0);
        request.setAttribute("logContent", "图片转pdf");

        try {
            log.debug(md5Paths + "drs");
            if (StringUtils.isBlank(pdfName) || md5Paths == null) {
                response.getOutputStream().write("图片转pdf".getBytes());
                response.getOutputStream().close();
                return;
            }
            boolean isIE = false;
            String userAgent = request.getHeader("User-Agent").toLowerCase();
            log.debug(userAgent + "userAgent");
            if (userAgent.indexOf("msie") != -1 || userAgent.indexOf("trident") != -1)
                isIE = true;
            fileService.imagesToPdf(md5Paths, pdfName, response, isIE, waterMark);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}